package org.manusoft.refill.service;

import java.util.ArrayList;
import java.util.Collection;

import org.manusoft.refill.domain.TUserDetailsRf;
import org.manusoft.refill.domain.TUserRoles;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("assembler")
public class Assembler {

  @Transactional(readOnly = true)
  User buildUserFromUserEntity(TUserDetailsRf userEntity) {

    String username = userEntity.getUserName();
    String password = userEntity.getPassword();
    boolean enabled = userEntity.isEnabled();
    boolean accountNonExpired = userEntity.isEnabled();
    boolean credentialsNonExpired = userEntity.isEnabled();
    boolean accountNonLocked = userEntity.isEnabled();

    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    for (TUserRoles role : userEntity.getTUserRolesCollection()) {
      authorities.add(new GrantedAuthorityImpl(role.getAuthority()));
    }

    User user = new User(username, password, enabled,
      accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
    return user;
  }
}